package model

import (
	"github.com/pkg/errors"
	"time"
)

type Record struct {
	Model          `xorm:"extends"`
	PlanID         uint       `json:"plan_id" xorm:"int notnull"`
	PlanName       string     `json:"plan_name" xorm:"varchar(50) notnull"`
	PipelineScript string     `json:"pipeline_script" xorm:"text notnull"`
	ExecHosts      string     `json:"exec_hosts" xorm:"varchar(50) notnull"`
	ExecResult     uint       `json:"exec_result" xorm:"int notnull"`
	PushKeys       string     `json:"push_keys" xorm:"varchar(100) notnull"`
	StartTime      *time.Time `json:"start_time" xorm:"datetime"`
	EndTime        *time.Time `json:"end_time" xorm:"datetime"`
}

var _ DBOperations = &Record{}

func (record *Record) Insert() (int64, error) {
	return DB.Insert(record)
}

func (record *Record) Update() (int64, error) {
	if record.ID == 0 {
		return 0, errors.New("id 为空！")
	}
	return DB.ID(record.ID).MustCols("exec_hosts", "exec_result", "start_time", "end_time").Update(record)
}

func (record *Record) Delete() (int64, error) {
	if record.ID == 0 {
		return 0, errors.New("id 为空！")
	}
	return DB.ID(record.ID).Delete(record)
}

func GetRecordByID(id uint) (*Record, error) {
	record := new(Record)
	has, err := DB.ID(id).Get(record)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return record, nil
}

func GetRecordByPushKeys(keys string) (*Record, error) {
	record := new(Record)
	has, err := DB.Where("push_keys = ?", keys).Get(record)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return record, nil
}
